$(document).ready(function() {
    var VAL ={
        NORMAL     : "0000000"  ,
        EVT_USER   : $("#userId").text(),
        T_XPTOOLOPE : "XPTOOLOPE" ,
        T_XPBISOPE  : "XPBISOPE" ,
        T_XPLSTEQP : "XPLSTEQP"
    };

    /**
     * All controls's jquery object/text
     * @type {Object}
     */
    var controlsQuery = {
        W                      : $(window)                    ,
        opeSelect              : $("#opeSelect")              ,
        toolSelect             : $("#toolSelect")             ,
        toolStatusSelect       : $("#toolStatusSelect")       ,
        statusChangeDatepicker : $("#statusChangeDatepicker") ,
        statusChangeTimepicker : $("#statusChangeTimepicker") ,
        remarkTxta             : $("#remarkTxta")             ,

        mainGrd   :{
            grdId     : $("#toolStatusInfoGrd")   ,
            grdPgText : "#toolStatusInfoPg"       ,
            fatherDiv : $("#toolStatusInfoDiv")
        }
    };

    /**
     * All button's jquery object
     * @type {Object}
     */
    var btnQuery = {
        f1 : $("#f1_btn"),
        f8 : $("#f8_btn")
    };

    /**
     * All tool functions
     * @type {Object}
     */
    var toolFunc = {
        resetJqgrid :function(){
            controlsQuery.W.unbind("onresize");
            controlsQuery.mainGrd.grdId.setGridWidth(controlsQuery.mainGrd.fatherDiv.width()*0.90);
            controlsQuery.W.bind("onresize", this);
        },
        clearInput : function(){
            controlsQuery.remarkTxta.val("");

        },

        /**
         * Set data for select
         * @param dataCnt
         * @param arr
         * @param selVal
         * @param queryObj
         */
        setSelectDate : function(dataCnt, arr, selVal, queryObj){
            var i, realCnt;

            queryObj.empty();
            realCnt = parseInt( dataCnt, 10);

            if( realCnt == 1 ){
                if( arr.hasOwnProperty(selVal)){
                    queryObj.append("<option value="+ arr[selVal] +">"+ arr[selVal] +"</option>")
                }
            }else if( realCnt > 1 ){
                for( i = 0; i < realCnt; i++ ){
                    if( arr[i].hasOwnProperty(selVal)){
                        queryObj.append("<option value="+ arr[i][selVal] +">"+ arr[i][selVal] +"</option>");
                    }
                }
            }
            queryObj.select2({
    	    	theme : "bootstrap"
    	    });
        },
        setOpeSelectDate : function(dataCnt, arr, selVal, selVal2, selVal3, selTxt, queryObj){
            var i, realCnt;

            queryObj.empty();
            realCnt = parseInt( dataCnt, 10);

            if( realCnt == 1 ){
                queryObj.append("<option value="+ arr[selVal] + "@" + arr[selVal2] + "@" + arr[selVal3] +">"+ arr[selTxt] +"</option>");
            }else if( realCnt > 1 ){
                for( i = 0; i < realCnt; i++ ){
                    queryObj.append("<option value="+ arr[i][selVal] + "@" + arr[i][selVal2] + "@" + arr[i][selVal3] +">"+ arr[i][selTxt] +"</option>");
                }
            }
            queryObj.select2({
    	    	theme : "bootstrap"
    	    });
        },
        /**
         * 根据人员，厂别，站点的关系，筛选出可以使用的站点.
         * @author CMJ
         */
        iniOpeSelect : function(){
        	var inObj, outObj;
            var user_id = VAL.EVT_USER;
            var iaryB = {
                user_id     : user_id
            }
            inObj = {
                trx_id      : VAL.T_XPBISOPE,
                action_flg  : 'I',
                iaryB       : iaryB
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                _setOpeSelectDate(outObj.tbl_cnt, outObj.oary, "ope_id", "ope_ver", "ope_dsc", controlsQuery.opeSelect);
            }
        },
        /**
         * 根据站点，人员，机台的关系；筛选出可以使用的机台.
         * @returns {Boolean}
         * @author CMJ
         */
        iniToolSelect : function(){
            var inObj, outObj, ope_id, ope_ver,
                ope_info, ope_info_ary;

            ope_info = $.trim(controlsQuery.opeSelect.val());

            if(!ope_info){
                return false;
            }

            ope_info_ary = ope_info.split("@");
            ope_id = ope_info_ary[0];
            ope_ver = ope_info_ary[1];

            if(!ope_id){
                console.error(ope_id);
                return false;
            }

            if(!ope_ver){
                console.error(ope_ver);
                return false;
            }
//            inObj = {
//                trx_id      : VAL.T_XPLSTEQP,
//                action_flg  : 'O'           ,
//                ope_id      : ope_id        ,
//                ope_ver     : ope_ver
//            };
//            inObj = {
//                trx_id      : VAL.T_XPLSTEQP,
//                action_flg  : 'L'           ,
//                ope_id      : ope_id        ,
//                ope_ver     : ope_ver       ,
//                user_id     : VAL.EVT_USER
//            };
            inObj = {
                    trx_id      : VAL.T_XPLSTEQP,
                    action_flg  : 'F'           ,
                    ope_id      : ope_id        ,
                    ope_ver     : ope_ver       ,
                    user_id     : VAL.EVT_USER  
                };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                _setSelectDate(outObj.tbl_cnt, outObj.oary, "tool_id", "tool_id", "#toolSelect", false);
            }
        },
        iniToolStatus : function(){
            addValueByDataCateFnc("#toolStatusSelect","EQST","data_id");
        },
        iniDateTimePicker : function(){
            var datepickerData, datepickerTime;
            controlsQuery.statusChangeDatepicker.datetimepicker({
                language: 'zh-CN',
                pickTime : false
            });
            controlsQuery.statusChangeTimepicker.datetimepicker({
                language: 'zh-CN',
                pickDate : false
            });

            datepickerData = controlsQuery.statusChangeDatepicker.data("datetimepicker");
            datepickerData.setLocalDate(datepickerData.getLocalDate());

            datepickerTime = controlsQuery.statusChangeTimepicker.data("datetimepicker");
            datepickerTime.setLocalDate(new Date());
        }
    }; 

    /**
     * All button click function
     * @type {Object}
     */
    var btnFunc = {
        //Query
        f1_func : function(){
            var inObj,
                outObj,
                tool_id;
            tool_id = controlsQuery.toolSelect.val();

            if(!tool_id){
                showErrorDialog("","请选择设备代码！");
                return false;
            }

            inObj = {
                trx_id      : VAL.T_XPTOOLOPE ,
                action_flg  : 'F'             ,
                tool_id     : tool_id
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                setGridInfo(outObj.oary,"#toolStatusInfoGrd");
            }
        },
        //Update
        f8_func : function(){
            var inObj,
                outObj,
                tool_id,
                tool_stat,
                remark,
                datepickerData,
                datepickerTime,
                evt_timestamp;
            tool_id = controlsQuery.toolSelect.val();
            remark = controlsQuery.remarkTxta.val();
            tool_stat = controlsQuery.toolStatusSelect.val();

            datepickerData = controlsQuery.statusChangeDatepicker.data("datetimepicker");
            datepickerTime = controlsQuery.statusChangeTimepicker.data("datetimepicker");

            evt_timestamp = datepickerData.getLocalDate().format('yyyy-MM-dd') + " " + datepickerTime.getLocalDate().format('hh:mm:ss');


            if(!tool_id){
                showErrorDialog("","请选择设备代码！");
                return false;
            }
            if(!remark){
                remark = "";
            }

            inObj = {
                trx_id      : VAL.T_XPTOOLOPE ,
                action_flg  : 'U'             ,
                tool_id     : tool_id         ,
                tool_stat   : tool_stat       ,
                evt_usr     : VAL.EVT_USER    ,
                remark      : remark          ,
                evt_timestamp : evt_timestamp
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                btnFunc.f1_func();
            }
        }
    };

    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        btnQuery.f1.click(function(){
            btnFunc.f1_func();
        });
        btnQuery.f8.click(function(){
            btnFunc.f8_func();
        });
    };

    /**
     * grid  initialization
     */
    var iniGridInfo = function(){
        var grdInfoCM = [
            {name: 'tool_id',          index: 'tool_id',          label: TOOL_ID_TAG               , width: 150},
            {name: 'tool_stat',        index: 'tool_stat',        label: TOOL_STATUS_TAG           , width: 60},
            {name: 'evt_timestamp',    index: 'evt_timestamp',    label: TOOL_STATUS_CHANGE_TAG    , width: 180},
            {name: 'pv_tool_stat',     index: 'pv_tool_stat',     label: PV_TOOL_STATUS_TAG        , width: 80},
            {name: 'pv_evt_timestamp', index: 'pv_evt_timestamp', label: PV_TOOL_STATUS_CHANGE_TAG , width: 180},
            {name: 'lKeep_time',       index: 'lKeep_time',       label: TOOL_STATUS_KEEP_TIME_TAG , width: 100},
            {name: 'evt_usr',          index: 'evt_usr',          label: EVT_USR                   , width: 150},
            {name: 'remark',           index: 'remark',           label: REMARK_TAG                , width: 500}
        ];
        controlsQuery.mainGrd.grdId.jqGrid({
            url:"",
            datatype:"local",
            mtype:"POST",
            height:300,
            width:650,
            shrinkToFit:false,
            scroll:true,
            rownumWidth : true,
            resizable : true,
            rowNum:40,
            loadonce:true,
            fixed:true,
            viewrecords:true,
            pager : controlsQuery.mainGrd.grdPgText,
            colModel: grdInfoCM
        });
    };

    /**
     * Other action bind
     */
    var otherActionBind = function(){
        // Reset size of jqgrid when window resize
        controlsQuery.W.resize(function(){
            toolFunc.resetJqgrid();
        });

        //Stop from auto commit
        $("form").submit(function(e){
            return false;
        });

        //Ope select change ==> tool auto refresh
        controlsQuery.opeSelect.change(function(){
            toolFunc.iniToolSelect();
        }); 

    };

    /**
     * Ini contorl's data
     */
    var iniContorlData = function(){
        toolFunc.clearInput();

        //Tool info
        toolFunc.iniOpeSelect();
        toolFunc.iniToolSelect();
        toolFunc.iniToolStatus();

        //Time
        toolFunc.iniDateTimePicker();
    };

    /**
     * Ini view, data and action bind
     */
    var initializationFunc = function(){
        iniGridInfo();
        iniButtonAction();
        otherActionBind();

        toolFunc.resetJqgrid();

        iniContorlData();
    };

    initializationFunc();
});

